package com.hmdp.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.constant.RedisConstants;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author MRS
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {

        //校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //校验不通过，返回信息
            return Result.fail("手机号格式错误！");
        }
        //生成验证码
        String code = RandomUtil.randomNumbers(6);

        //存session
        // session.setAttribute("code", code);

        //把验证码存入redis中login:code:手机号 验证码 ttl:2分钟
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY + phone, code, RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);

        //发送验证码
        log.debug("发送短信验证码成功，验证码：{}", code);


        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {

        String phone = loginForm.getPhone();

        //校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //校验不通过，返回信息
            return Result.fail("手机号格式错误！");
        }

        //校验验证码
        String code = loginForm.getCode();
        // String cacheCode = session.getAttribute("code").toString();

        //Redis校验验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);

        if (cacheCode == null || !cacheCode.equals(code)) {
            //返回错误信息
            return Result.fail("验证码错误！");
        }

        //根据手机号查询用户【查询不到即注册用户】
        User user = query().eq("phone", phone).one();

        if (user == null) {
            //用户注册并入库
            user = createUserWithPhone(phone);
        }


        //防止敏感信息泄露
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //保存用户信息到session
        // session.setAttribute("user", userDTO);

        //将用户信息存入到Redis中
        //随机token作为key，作为登录令牌
        String token = UUID.randomUUID().toString(true);
        //将Bean转换为Map  Object bean, Map<String, Object> targetMap, CopyOptions copyOptions
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(), CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((fieldName, fieldValue)->{
                    return fieldValue.toString();
                })
        );
        //1. userMap.replace("id", userMap.get("id").toString());
        //2. userMap.forEach((k,v)->{
        //     // v.toString();
        //     StrUtil.toString(v);
        // });

        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
        //随着用户的增加，Redis存储空间占用会变大  【设置过期时间30分钟】
        stringRedisTemplate.expire(tokenKey, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //返回token
        return Result.ok(token);
    }

    private User createUserWithPhone(String phone) {
        User user = User.builder()
                .phone(phone)
                .nickName("user_" + RandomUtil.randomString(10))
                .build();
        save(user);
        return user;
    }
}
